Rewrite encode/decode logic to use BigInt and bitwise operators.#29
Rewrite encode/decode logic to use BigInt and bitwise operators.#29
Conversation
Improves permission granting and revoking by using BigInt operations for better performance and readability. Simplifies encoding and decoding processes for improved efficiency.
Updates the TypeScript compilation target to ES2020, enabling the use of newer ECMAScript features. Adds a new test case to Aclatraz.test.ts for exploring ACL code generation with a predefined set of rule IDs, allowing for more thorough testing and validation of the code generation logic.
Introduces performance tests to evaluate the efficiency of various Aclatraz operations such as code generation, permission granting, verification, and revocation. These tests help identify potential performance bottlenecks and ensure the library scales effectively with a large number of rules.
Updates development dependencies to the latest versions. This ensures compatibility with the newest features and bug fixes in the tooling ecosystem.
WalkthroughThe updates include major version bumps for development dependencies, a TypeScript target upgrade to ES2020, and significant internal refactoring of the Changes
Sequence Diagram(s)sequenceDiagram
participant TestSuite as Test Suite
participant Aclatraz as Aclatraz Instance
TestSuite->>Aclatraz: addRules(rules)
TestSuite->>Aclatraz: grantPermission(ruleIds)
Aclatraz->>Aclatraz: Encode permissions using BigInt
Aclatraz-->>TestSuite: permissionCode
TestSuite->>Aclatraz: verify(permissionCode, ruleId)
Aclatraz->>Aclatraz: Decode with BigInt, check bit
Aclatraz-->>TestSuite: verificationResult
TestSuite->>Aclatraz: revokePermission(permissionCode, ruleIds)
Aclatraz->>Aclatraz: Decode with BigInt, clear bits, re-encode
Aclatraz-->>TestSuite: updatedPermissionCode
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
Updates the Node.js versions used in the test workflow to align with current supported versions. This ensures compatibility and reliable testing against the latest Node.js releases.
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (7)
src/Aclatraz.performance.test.ts (4)
24-41: Enhance test with more meaningful assertions.The performance test measures granting permissions 100,000 times but uses a trivial assertion (
expect(true).toBe(true)).test('grantPermission 100,000 times', () => { const rules = []; for (let i = 1; i <= 100; i++) { rules.push({ id: i, slug: `rule${i}` }); } const acl = new Aclatraz(rules); const ruleIds = Array.from({ length: 100 }, (_, i) => i + 1); + const permissionResults = []; const start = performance.now(); for (let i = 0; i < 100000; i++) { - acl.grantPermission('', ruleIds); + permissionResults.push(acl.grantPermission('', ruleIds)); } const end = performance.now(); console.log( `grantPermission 100,000 times took: ${(end - start).toFixed(2)} ms` ); - expect(true).toBe(true); + // Verify all permission codes are identical (deterministic) + expect(new Set(permissionResults).size).toBe(1); + // Verify the permission code is valid + expect(permissionResults[0].length).toBeGreaterThan(0); });
43-61: Improve verify test with meaningful assertions.The performance test for verification uses a trivial assertion and doesn't validate the actual behavior.
test('verify (decode) 100,000 times', () => { const rules = []; for (let i = 1; i <= 100; i++) { rules.push({ id: i, slug: `rule${i}` }); } const acl = new Aclatraz(rules); const ruleIds = Array.from({ length: 100 }, (_, i) => i + 1); const permission = acl.grantPermission('', ruleIds); + let verifyResults = []; const start = performance.now(); for (let i = 0; i < 100000; i++) { - acl.verify(permission, 50); // Arbitrary ruleId in the middle + verifyResults.push(acl.verify(permission, 50)); // Arbitrary ruleId in the middle } const end = performance.now(); console.log( `verify (decode) 100,000 times took: ${(end - start).toFixed(2)} ms` ); - expect(true).toBe(true); + // All verifications should return true since rule 50 is in the permission + expect(verifyResults.every(result => result === true)).toBe(true); + + // Verify that a non-existent rule returns false + expect(acl.verify(permission, 101)).toBe(false); });
63-81: Add meaningful assertions to revokePermission test.The performance test for revoking permissions doesn't validate the actual behavior.
test('revokePermission 100,000 times', () => { const rules = []; for (let i = 1; i <= 100; i++) { rules.push({ id: i, slug: `rule${i}` }); } const acl = new Aclatraz(rules); const ruleIds = Array.from({ length: 100 }, (_, i) => i + 1); const permission = acl.grantPermission('', ruleIds); + const finalPermission = permission; const start = performance.now(); for (let i = 0; i < 100000; i++) { - acl.revokePermission(permission, [50]); // Arbitrary ruleId + const result = acl.revokePermission(permission, [50]); // Arbitrary ruleId + if (i === 99999) finalPermission = result; } const end = performance.now(); console.log( `revokePermission 100,000 times took: ${(end - start).toFixed(2)} ms` ); - expect(true).toBe(true); + // Verify rule 50 is revoked in the final permission + expect(acl.verify(finalPermission, 50)).toBe(false); + + // Other rules should still be present + expect(acl.verify(finalPermission, 49)).toBe(true); + expect(acl.verify(finalPermission, 51)).toBe(true); });
83-144: Consider using consistent loop structures across tests.The final three performance tests use very similar structures but slightly different approaches to iteration. For example, the verification test checks every 10,000th rule, but the others don't use sampling.
For better maintainability, consider standardizing the approach across all large-scale tests by:
- Using consistent sampling methods
- Adopting similar patterns for creating rule sets
- Using similar assertion patterns
src/Aclatraz.ts (3)
88-104: Avoid double ‑conversion: decode() → string → BigInt → string again
grantPermission()converts the existing permission from an encoded string
to a padded binary string (decode()), then immediately back to aBigInt
only to stringify it again when callingencode().
This causes two unnecessary string/BigIntround-trips on every call.A lighter path is to keep the number as
BigIntall the way through:- let aclNumber = BigInt(`0b${this.decode(currentPermission)}`); + // decode directly to BigInt to avoid extra conversions + let aclNumber = this.decodeToBigInt(currentPermission); ... - return this.encode(aclNumber.toString(2), this.options.chunkSize); + return this.encodeFromBigInt(aclNumber);You already have all the building blocks inside
encode()/decode(); a pair
of thin wrappers (decodeToBigInt,encodeFromBigInt) would make the core
logic faster (no string copies) and easier to read.
111-127: Symmetric improvements recommended forrevokePermission()The same conversion chain discussed above is repeated here.
Once helper methods that operate directly onBigIntexist,
revokePermission()can mirror the streamlined flow and avoid the
current overhead.
169-175:padStartmay add superfluous leading zerosAfter assembling the full
aclNumber, you pad it to
chunkSize * chunks.length.
If the most-significant chunk is not fully utilised (very common), this
adds extra zeros that will later be re-encoded, lengthening the permission
string unnecessarily.A safer variant is to
trimStart()after padding or compute the minimal
bit-length needed.This keeps encodings compact without losing information.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (5)
package.json(1 hunks)src/Aclatraz.performance.test.ts(1 hunks)src/Aclatraz.test.ts(1 hunks)src/Aclatraz.ts(4 hunks)tsconfig.json(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/Aclatraz.test.ts (1)
src/Aclatraz.ts (1)
Aclatraz(6-187)
src/Aclatraz.performance.test.ts (1)
src/Aclatraz.ts (1)
Aclatraz(6-187)
🔇 Additional comments (4)
tsconfig.json (1)
7-7: Target upgrade enables BigInt support.The update to ES2020 target is necessary for BigInt support, which aligns perfectly with the objective of using bitwise operators for encode/decode logic in the Aclatraz class.
src/Aclatraz.performance.test.ts (2)
1-22: Performance test properly measures code generation.Good use of the
performanceAPI for benchmarking. This test validates generation of permission codes with 10,000 rules.
102-123: Well-structured large-scale verification test.This test correctly measures performance for verifying permissions with 100,000 rules and includes an assertion that checks the correct number of rules were found. Good implementation.
src/Aclatraz.ts (1)
135-139:encode()– special-case for zero is correct, but loses configurabilityReturning a hard-wired chunk of
'0'.repeat(this.options.padding)works only
whenoptions.encoding === 16.
If a caller changes the encoding (e.g. base-36), the zero chunk will still be
rendered in base-10 digits, breaking the round-trip withdecode().Consider delegating the zero case to the generic loop so the representation
automatically adapts to the active encoding:- if (aclNumber === 0n) { - return '0'.repeat(this.options.padding); - } + if (aclNumber === 0n) { + return (0n) + .toString(this.options.encoding) + .padStart(this.options.padding, this.options.paddingChar); + }
| "@types/jest": "^29.5.11", | ||
| "@types/node": "^20.11.30", | ||
| "@typescript-eslint/eslint-plugin": "^7.7.0", | ||
| "@typescript-eslint/parser": "^7.7.0", | ||
| "eslint": "^8.57.0", | ||
| "eslint-config-prettier": "^9.1.0", | ||
| "eslint-plugin-jest": "^27.9.0", | ||
| "jest": "^29.7.0", | ||
| "np": "^8.0.4", | ||
| "rimraf": "^5.0.5", | ||
| "ts-jest": "^29.1.1", | ||
| "ts-node": "^10.9.2", | ||
| "typescript": "^5.4.5" |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Verify npm compatibility with major dependency upgrades.
The significant version bumps across all development dependencies are necessary to support ES2020 features like BigInt, but may require adjustments to CI/CD workflows or developer environments.
🏁 Script executed:
#!/bin/bash
# Check compatibility with current Node.js LTS versions
echo "Checking Node.js compatibility information"
grep -A 5 "engines" package.json || echo "No engines field specified in package.json"
# Check if any dependencies have compatibility warnings
npm ls --depth=0 || echo "Some dependencies might have compatibility issues"Length of output: 315
🏁 Script executed:
#!/bin/bash
# Locate the package.json in the repository
fd --max-depth 2 package.json || find . -maxdepth 2 -name package.json
# Inspect for an "engines" field to lock Node.js versions
grep -R '"engines"' -n package.json || echo "No engines field in package.json"
# Check GitHub Actions workflows for Node version pins
grep -R "node-version" -n .github/workflows/ || echo "No node-version specification in workflows"Length of output: 522
Add a Node.js engines field and update CI Node versions
To ensure developers and CI use a compatible Node.js version for these upgraded dev dependencies:
• In package.json, add an "engines" section (e.g. "node": ">=16") to lock the minimum Node.js version.
• In .github/workflows/test.yml, bump the node-version matrix to current LTS releases (e.g. 16.x, 18.x, 20.x), replacing the old 10.x, 12.x, 14.x, 15.x entries.
• Verify local environments are running Node.js ≥16 before installing.
These changes will align your CI/CD and developer machines with the requirements of TypeScript 5.4+, ESLint 8.x, and other modern tooling.
There was a problem hiding this comment.
Pull Request Overview
This PR rewrites the encode/decode logic to use BigInt and bitwise operators for improved efficiency and adds performance tests for large-scale permission operations. Key changes include:
- Replacing array-based binary manipulation with BigInt bitwise operations in grantPermission, revokePermission, encode, and decode.
- Enhancing tests with additional cases and performance benchmarks for different permission operations.
- Updating the CI workflow to use newer Node.js versions.
Reviewed Changes
Copilot reviewed 6 out of 7 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| src/Aclatraz.ts | Rewritten encode/decode logic using BigInt and bitwise manipulations. |
| src/Aclatraz.test.ts | Added new test cases and updated existing tests. |
| src/Aclatraz.performance.test.ts | Introduced performance tests for permission operations. |
| .github/workflows/test.yml | Updated Node.js versions for continuous integration. |
Files not reviewed (1)
- package.json: Language not supported
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Adds a comprehensive integration test to verify the encoding and decoding of a set of rules within Aclatraz. This test ensures that adding, encoding, and verifying a collection of rule IDs functions correctly, increasing confidence in the overall reliability of the Aclatraz system.
Specifies the minimum Node.js version required to run the package, ensuring compatibility and preventing potential issues with older Node.js versions.
Adds validation to ensure the `chunkSize` option does not exceed 128, preventing potential issues with large chunk sizes. Updates option setting logic to include the new validation.
Enables the library to handle ACL chunks encoded in formats other than hexadecimal, providing more flexibility in processing ACL data.
Adds tests to cover edge cases, specifically constructor chunk size validation and non-hex encoding support. This improves code robustness and test coverage.
Adds tests and implementations to better handle different encoding options, chunk sizes, and padding configurations. This increases the flexibility and robustness of Aclatraz permission management. Also prevents `chunkSize` from being set to a value larger than 128 to avoid unexpected behavior.
Updates the code coverage action to the latest version. This ensures compatibility with newer environments and potentially includes performance improvements and bug fixes. Adds CODECOV_TOKEN environment variable.
Codecov ReportAll modified and coverable lines are covered by tests ✅
Additional details and impacted files@@ Coverage Diff @@
## main #29 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 2 2
Lines 90 119 +29
Branches 13 25 +12
=========================================
+ Hits 90 119 +29 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
Summary by CodeRabbit
New Features
Refactor
Chores